package com.yh.ldzl.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.UR;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.core.web.page.TableSupport;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.BasicService;
import com.ruoyi.system.api.InventoryService;
import com.yh.ldzl.service.QcTemplateProductService;
import org.apache.ibatis.annotations.Param;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yh.ldzl.mapper.QcIqcMapper;
import com.yh.ldzl.domain.QcIqc;
import com.yh.ldzl.service.IQcIqcService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * ldzl-qcService业务层处理
 * 
 * @author yanghuai
 * @date 2025-07-02
 */
@Service
public class QcIqcServiceImpl implements IQcIqcService 
{
    @Autowired
    private QcIqcMapper qcIqcMapper;

    @Autowired
    private QcTemplateProductService qcTemplateProductService;

    @Resource
    private InventoryService inventoryService;
    @Resource
    private BasicService basicService;
    /**
     * 自动编码
     */
    private String generateCode(Long type) {
        // 调用远程服务（消费模式，确保每次调用都会递增流水号）
        AjaxResult codeResult = basicService.automaticallyNumbersConsume(type);

        // 确保远程调用返回了结果对象
        if (codeResult == null) {
            throw new ServiceException(String.format("远程获取编码调用失败，返回结果为空，类型: %d", type));
        }

        // 根据该接口的特殊设计，编码直接存放在msg字段
        Object msg = codeResult.get(AjaxResult.MSG_TAG);
        Object code = codeResult.get(AjaxResult.CODE_TAG);
        System.out.println("编码是：" + code);
        // 确保编码内容不为空
        if (msg == null || msg.toString().isEmpty()) {
            throw new ServiceException(String.format("远程获取编码成功，但返回的编码为空，类型: %d, 返回信息: %s", type, msg));
        }

        // 从AjaxResult中正确取出msg部分作为编码
        return msg.toString();
    }

    /**
     * 查询ldzl-qc
     * 
     * @param iqcId ldzl-qc主键
     * @return ldzl-qc
     */
    @Override
    public QcIqc selectQcIqcByIqcId(Long iqcId)
    {
        return qcIqcMapper.selectQcIqcByIqcId(iqcId);
    }

    /**
     * 查询ldzl-qc列表
     * 
     * @param qcIqc ldzl-qc
     * @return ldzl-qc
     */
    @Override
    public List<QcIqc> selectQcIqcList(QcIqc qcIqc)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        return qcIqcMapper.selectQcIqcList(qcIqc);
    }

    /**
     * 新增ldzl-qc
     * 
     * @param qcIqc ldzl-qc
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertQcIqc(QcIqc qcIqc) {
        int success=0;
        try{
            qcIqc.setCreateBy(SecurityUtils.getUsername());
            TableDataInfo receipt = inventoryService.findReceipt_id_qc(qcIqc.getSourceDocId());
            List<?> list = receipt.getRows();
            List<Map<String, Object>> list1 = (List<Map<String, Object>>) list;
            System.out.println("list1 = " + list1);
            int totalRows = 0;
            for (int i = 0; i < list1.size(); i++) {
                Map<String, Object> map = list1.get(i);

                // 只在第一次循环之后生成编码
                if (i != 0) {
                    String codeResult = generateCode(9L);
                    qcIqc.setIqcCode(codeResult);
                }
                qcIqc.setGoodsCode(map.get("goods_code").toString());
                qcIqc.setGoodsName(map.get("goods_name").toString());
                qcIqc.setStockSfn(map.get("stock_sfn").toString());
                qcIqc.setUnitName(map.get("unit_name").toString());
                String receivedNumStr = map.get("recived_num").toString();
                BigDecimal receivedNum = new BigDecimal(receivedNumStr);
                qcIqc.setQuantityRecivedNum(receivedNum);
                totalRows += qcIqcMapper.insertQcIqc(qcIqc);
            }
            success = totalRows == list.size() ? 1 : 0;


        }catch (Exception e){
            return 0;   // 1-全部成功，0-失败
        }
        return success;   // 1-全部成功，0-失败


    }

    /**
     * 修改ldzl-qc
     * 
     * @param qcIqc ldzl-qc
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateQcIqc(QcIqc qcIqc) {
        qcIqc.setUpdateBy(SecurityUtils.getUsername());

        // 1. 查询 line_id
        Long line_id = qcIqcMapper.selectCkItemRecptLineLineId(
                qcIqc.getSourceDocId(), qcIqc.getGoodsCode());
        System.out.println("line_id:" + line_id);

        // 2. 更新主表
        int row1 = qcIqcMapper.updateQcIqc(qcIqc);
        int row2=0;
        // 3. 更新明细状态
        if (qcIqc.getCheckResult().equals("1")){//检测单合格
            row2 = qcIqcMapper.updateCkItemRecptLineStatus(
                    line_id, "2", qcIqc.getIqcId());//将入库单明细状态改为合格
        }else if (qcIqc.getCheckResult().equals("2")){//检测单不合格
            row2 = qcIqcMapper.updateCkItemRecptLineStatus(
                    line_id, "3", qcIqc.getIqcId());//将入库单明细状态改为不合格
        }

        //判断出货单明细检测情况
        int testResults = qcIqcMapper.selectCkItemRecptTestResults(qcIqc.getSourceDocId());
        if (testResults==1) {//1.全部合格(所有行都已质检且状态为2/合格)
            inventoryService.updateCkProductRecptStatusStatus(qcIqc.getSourceDocId(),3L);
        }else if (testResults==2) {//2.全部不合格(所有行都已质检且状态为3/不合格)
            inventoryService.updateCkProductRecptStatusStatus(qcIqc.getSourceDocId(),4L);
        }else if (testResults==4) {//4.有合格也有不合格(存在合格和不合格的行，且没有未质检的行)
            inventoryService.updateCkProductRecptStatusStatus(qcIqc.getSourceDocId(),5L);
        }

        System.out.println("更新入库表:"+testResults+ "更新入库检测表:"+row1+ "更新入库详情表:"+row2);
        // 4. 必须都大于 0 才算成功
        return (row1 > 0 && row2 > 0) ? 1 : 0;
    }

    /**
     * 批量删除ldzl-qc
     * 
     * @param iqcIds 需要删除的ldzl-qc主键
     * @return 结果
     */
    @Override
    public int deleteQcIqcByIqcIds(Long[] iqcIds)
    {

        return qcIqcMapper.deleteQcIqcByIqcIds(iqcIds);
    }

    /**
     * 删除ldzl-qc信息
     * 
     * @param iqcId ldzl-qc主键
     * @return 结果
     */
    @Override
    public int deleteQcIqcByIqcId(Long iqcId)
    {
        return qcIqcMapper.deleteQcIqcByIqcId(iqcId);
    }

    @Override
    public boolean selectQcIqcCodeUnique(int source_doc_id,String material_code) {
        return qcIqcMapper.selectQcIqcCodeUnique(source_doc_id,material_code)==0;
    }

    @Override
    public boolean selectQcIqcLineCodeUnique(String iqc_code) {
        return qcIqcMapper.selectQcIqcLineCodeUnique(iqc_code)==0;
    }

    @Override
    public QcIqc selectQcIqcDetail(String source_doc_code) {
        return qcIqcMapper.selectQcIqcDetail(source_doc_code);
    }

    @Override
    public QcIqc selectQcIqcId(Long source_doc_id) {
        return qcIqcMapper.selectQcIqcId(source_doc_id);
    }

    @Override
        public List<Map<String, Object>> selectCkProductRecptDetectSingle(String recpt_code,String recpt_name) {
        return qcIqcMapper.selectCkProductRecptDetectSingle(recpt_code,recpt_name);
    }

    @Override
    public List<Map<String, Object>> selectCkProductRecptGoodsCode(Long recpt_id) {
            return qcIqcMapper.selectCkProductRecptGoodsCode(recpt_id);
    }


}
